package com.ygou.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ygou.pojo.Cart;
import com.ygou.service.CartService;

@Controller
@RequestMapping(value="/cart")
public class CartController {
	@Autowired
	private CartService cartService;
	
	/**
	 * 添加商品到购物车
	 * @param cart
	 * @return
	 */
	@RequestMapping(value="/addCart",produces="application/json;charset=UTF-8")
	public @ResponseBody boolean addCart(Cart cart){
		return cartService.addCart(cart);
	}
	
	@RequestMapping(value="/findCartByUId")
	public String findCartByUid(Integer userid,HttpSession session){
		List<Cart> carts=cartService.findCartByUId(userid);
		session.setAttribute("carts",carts);
		//model.put("carts",carts);
 		return "redirect:/cart.jsp";
	}
	
	/**
	 * 修改商品数量
	 * @param cartid
	 * @param goodscount
	 * @param goodsprice
	 * @return
	 */
	@RequestMapping(value="/updCartInfo",produces="application/json;charset=UTF-8")
	public @ResponseBody boolean updCartInfo(Integer cartid,Integer goodscount,BigDecimal goodsprice){
		Cart cart=cartService.selectByPrimaryKey(cartid);
		cart.setGoodscount(goodscount);
		cart.setGoodsprice(goodsprice);
		cart.setGoodstotalprice(goodsprice.multiply(new BigDecimal(goodscount)).setScale(2, BigDecimal.ROUND_HALF_UP));
		return cartService.updCartInfo(cart);
	}
	
	@RequestMapping(value="/delCart",produces="application/json;charset=UTF-8")
	public @ResponseBody boolean delCartById(@RequestParam(required=false)List<Integer> cartids,
			@RequestParam(required=false)Integer cartid){
		if (cartids==null){
			cartids=new ArrayList<Integer>();
			cartids.add(cartid);
		}
		return cartService.delCart(cartids);
	}
}
